package controllers;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import models.*;
import helpers.*;
import models.Class;
import play.mvc.Controller;
import play.mvc.With;

@With(Secure.class) 

public class Attendance extends Controller {
	
	public static void takeAttendanceS(Long class_id , Byte a, String date) {
		
		Class c = Class.findById(class_id);
		c.studentAttendance(a);		
		c.save();
		c.registration.save();
		viewClasses(date);
	}
	
	public static void takeAttendanceT(Long class_id , Byte a, String date) {
		
		Class c = Class.findById(class_id);
		c.teacherAttendance(a);
		c.save();
		c.registration.save();
		viewClasses(date);
	}
	
	public static void viewClasses(String date) {
		
		flash.clear();
		
		if(Register.count() == 0) {
            flash.error("No registrations in database");
            Application.index();
        }
		
		Date d;
        SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
		try {
			d = formatter.parse(date);
			
		} catch (Exception e) {
			
			d = new Date();
			date = d.getDate()+"/"+(d.getMonth()+1)+"/"+(d.getYear()+1900);
			
		}
		
		LinkedList<LinkedList<Class>> classes = new LinkedList<LinkedList<Class>>() ;
		List<Activity> activities = Activity.findAll();
		
		for(int i=0 ; i<activities.size() ; i++) 
		{
			LinkedList<Class> cs = activities.get(i).getActivityClasses(d);
			if (cs.size() > 0) classes.add(cs);
		
		}
		render(classes,date);
		
		
	}
	
	@SuppressWarnings("deprecation")
	public static void getSalary(Long id) {
		
		if(Teacher.count() == 0) {
            flash.error("No Teachers in database");
            Application.index();
        }
		
		String date = Payement.dateMonth();
		
		Teacher t = (Teacher) ((id!=null)?Teacher.findById(id):Teacher.findAll().get(0));
		List<Class> cs = t.getAttendedClasses(new Date().getMonth());
		
		int at = t.getAttendedClasses(new Date().getMonth()).size();
		
		int amount = t.calculateThisMonthSalary();
		
		if(t.salaries == null) {
			t.salaries = new LinkedList<Salary>();
			t.save();
		}
			
		int salary = (t.salaries.size()>0)?t.salaries.get(t.salaries.size()-1).amount:0;
		
		Float per = t.percentage;
		
		render(id,cs,at,amount,salary,per,date);
		
				
	}
	
	public static void setSalary(Long id, int amount) {
		
		Teacher t = Teacher.findById(id);
		t.setSalary(amount).save();
		t.save();
		getSalary(id);
		
	}
	
	public static void setPercentage(Long id, Float amount) {
		
		Teacher t = Teacher.findById(id);
		t.percentage  = amount;
		t.save();
		getSalary(id);
	}
	
			
	
	

}
